<script>
	import {
		ST_TOKEN,
		VOICE_KEY,
		SHOCK_KEY,
		SHOCK_TIME
	} from './constants/index'
	import store from './store';
//	const dcRichAlert = uni.requireNativePlugin('DCloud-RichAlert')
	export default {
		data() {
			return {
				appPlatform_Info: "",
			}
		},
		onLaunch: function() {
			const _self = this;
			//var info = plus.push.getClientInfo();
			/* plus.push.getClientInfoAsync(function(info) {
				console.log('succ', info);
			}, function(err) {
				console.log('err', err);
			}); */
			this.initToken();

			 const jyJPush = uni.requireNativePlugin('JY-JPush'); //插件中心购买
			jyJPush.setJYJPushAlias({
				userAlias: 'userAlias'
			}, result => {
				//console.log(JSON.stringify(result))
				//  设置成功或者失败，都会通过这个result回调返回数据；数据格式保持极光返回的安卓/iOS数据一致
				//  注：若没有返回任何数据，考虑是否初始化完成
			});

			 jyJPush.getRegistrationID(
				//  返回的数据会有registrationID，errorCode
				result => {
					console.log("registrationID",JSON.stringify(result))
			});
			/* jyJPush.addJYJPushCustomReceiveNotificationListener(result => {
				_self.appPlatform_Info = JSON.parse(result.message);
				_self.$forceUpdate();
				_handlePush(_self.appPlatform_Info);
			}); */

			// App平台检测升级，服务端代码是通过uniCloud的云函数实现的，详情可参考：https://ext.dcloud.net.cn/plugin?id=2226
			if (plus.runtime.appid !== 'HBuilder') { // 真机运行不需要检查更新，真机运行时appid固定为'HBuilder'，这是调试基座的appid
				uni.request({
					url: 'https://7a3e3fa9-7820-41d0-be80-11927ac2026c.bspapp.com/http/update', //检查更新的服务器地址
					data: {
						appid: plus.runtime.appid,
						version: plus.runtime.version,
						imei: plus.device.imei
					},
					success: (res) => {
						if (res.statusCode == 200 && res.data.isUpdate) {
							// 提醒用户更新
							uni.showModal({
								title: '更新提示',
								content: res.data.note ? res.data.note : '是否选择更新',
								success: (ee) => {
									if (ee.confirm) {
										plus.runtime.openURL(res.data.url);
									}
								}
							})
						}
					}
				})
			}

			 plus.push.addEventListener('click', function(message) {
				console.log('click', message)
				uni.switchTab({
					url: '/pages/grab/list'
				})
			});
			plus.push.addEventListener('receive', function(message) {
				_self.appPlatform_Info = message.payload;
				_self.$forceUpdate();

				_handlePush(message);
			}); 

			const _handlePush = function(message) {
				let voiceFlag = uni.getStorageSync(VOICE_KEY) || true
				let shockFlag = uni.getStorageSync(SHOCK_KEY) || true
				let shockTime = uni.getStorageSync(SHOCK_TIME) || 2
				// 调起手机震动
				if (shockFlag) {
					let i = 0;
					if (_self.appPlatform_Info != null && _self.appPlatform_Info.code == 4) {
						let index = setInterval(function() {
							++i;
							if (i === shockTime) {
								clearInterval(index)
							}
							uni.vibrateLong({
								success: function() {
									console.log('震动success');
								}
							});
						}, 1000);
					}
				}
				// 播放音频
				if (voiceFlag) {
					var main = plus.android.runtimeMainActivity();
					var SpeechUtility = plus.android.importClass('com.iflytek.cloud.SpeechUtility');
					//这里的appid填你自己申请的
					SpeechUtility.createUtility(main, "appid=60277223");
					var SynthesizerPlayer = plus.android.importClass('com.iflytek.cloud.SpeechSynthesizer');
					var play = SynthesizerPlayer.createSynthesizer(main, null);

					if (_self.appPlatform_Info != null && _self.appPlatform_Info.code == 4) {
						play.startSpeaking(_self.changeEnCode(_self.appPlatform_Info.message), null);
					}
				}
			}
		},onShow: function() {
			//console.log('App Show')
			// this.initSocket();
		},
		onHide: function() {
			//console.log('App Hide')
			// 关闭websocket
			uni.closeSocket();
		},
		globalData: {
			test: ''
		},
		methods: {
			initToken() {
				uni.getStorage({
					key: ST_TOKEN,
					success: function(res) {
						store.state.token = res.data
					}
				});
			},initSocket() {
				let _this = this;
				try {
					// WebSocket的地址
					let url = 'ws://127.0.0.1:9000/ws/member/' + uni.getStorageSync(ST_TOKEN);
					// 连接
					uni.connectSocket({
						url: url,
						fail: (err) => {
							//	console.log(err)
						}
					});
					// 监听连接打开
					uni.onSocketOpen(function(res) {
						//console.log('WebSocket打开');
					});
					// 监听WebSocket错误
					uni.onSocketError(function(res) {
						//console.log('WebSocket连接打开失败，请检查！');
					});
					// 监听连接关闭
					uni.onSocketClose(function(e) {
						//console.log('WebSocket连接关闭！');
					});
					// 监听收到信息
					uni.onSocketMessage(function(res) {
						let serverData = JSON.parse(res.data)
						//console.log(new Date())
						//	console.log(serverData)
						if (serverData.type === 'NEED_LOGIN') {

						}
						//与后端规定好返回值分别代表什么，写业务逻辑
					})
				} catch (e) {}
			},sendMsg(msg) {
				uni.sendSocketMessage({
					data: msg
				});
			},changeEnCode(str) {
				let res = []
				for (let i = 0; i < str.length; i++) {
					// 这个不是正常的encodeUnicode 颠倒了大小端的位置  
					res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-2) + ("00" + str.charCodeAt(i).toString(16)).slice(-4, -2)
				}
				let strCode = "\\u" + res.join("\\u")
				strCode = strCode.replace(/\\/g, "%")
				return unescape(strCode);
			}
		}
	}
</script>

<style>
	/* @import '/static/iconfont/iconfont.css'; */
	/* @import url("./static/iconfont/iconfont-weapp-icon.css"); */
	/* uni.css - 通用组件、模板样式库，可以当作一套ui库应用 */
	@import './common/uni.css';

	/* 以下样式用于 hello uni-app 演示所需 */
	page {
		background-color: #f7f7f7;
		height: 100%;
		font-size: 28rpx;
		line-height: 1.8;
	}

	.uni-header-logo {
		padding: 30rpx;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		margin-top: 10rpx;
	}

	.uni-header-image {
		width: 100px;
		height: 100px;
	}

	.uni-hello-text {
		color: #7A7E83;
	}

	.uni-hello-addfile {
		text-align: center;
		line-height: 300rpx;
		background: #FFF;
		padding: 50rpx;
		margin-top: 10px;
		font-size: 38rpx;
		color: #808080;
	}

	uni-checkbox .uni-checkbox-input {
		border-radius: 50%;
	}

	uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked {
		border: 1rpx solid rgb(253, 103, 3);
		background-color: rgb(253, 103, 3);
	}

	uni-checkbox .uni-checkbox-wrapper {
		width: 100%;
	}

	uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked:before {
		color: #FFFFFF;
	}

	uni-checkbox:not([disabled]) .uni-checkbox-input:hover {
		border-color: transparent;
	}
</style>
